<?php

namespace addons\groupon\listener\order;

use addons\groupon\model\Order;
use addons\groupon\model\Coupons;
use addons\groupon\model\UserCoupons;

/**
 * 优惠券
 */
class Coupon
{
    /**
     * 订单支付成功
     *
     * @param [type] $params
     * @return void
     */
    public function grouponOrderPayedAfter(&$params)
    {
        $order = $params['order'];

        // 检测并赠送优惠券
        $this->checkAndGift($order, 'payed');
    }


    /**
     * 订单全部确认收货
     *
     * @param [type] $params
     * @return void
     */
    public function grouponOrderConfirmFinish(&$params) 
    {
        $order = $params['order'];

        // 检测并赠送优惠券
        $this->checkAndGift($order, 'confirm');
    }


    /**
     * 订单完成，评价完成
     *
     * @param [type] $params
     * @return void
     */
    public function grouponOrderFinish(&$params) 
    {
        $order = $params['order'];

        // 检测并赠送优惠券
        $this->checkAndGift($order, 'finish');
    }


    public function checkAndGift($order, $event) {
        // 重新查询订单
        $order = Order::where('id', $order['id'])->lock(true)->find();      // 加锁读，防止重复执行
        $ext = $order['ext_arr'];
        $coupon_ids = $ext['activity_gift_coupon_ids'] ?? '';
        $activity_discount_infos = $ext['activity_discount_infos'] ?? '';
        $couponIds = array_values(array_filter(explode(',', $coupon_ids)));     // 不能有空值，但可以重复（多个商品赠送同一个优惠券时）

        // 要赠送优惠券，并且还没赠送
        if ($couponIds) {
            // 循环订单参与的活动，找到赠送优惠券的活动
            foreach ($activity_discount_infos as $key => $info) {
                if (!in_array($info['activity_type'], ['full_gift'])) {
                    continue;
                }

                // 不是设置的触发条件
                if ($info['event'] != $event) {
                    continue;
                }

                // 要赠送的优惠券,重复只赠送一次
                $current_coupon_ids = $info['discount_rule']['coupons_ids'] ? array_values(array_unique(array_filter(explode(',', $info['discount_rule']['coupons_ids'])))) : [];
                if (!$current_coupon_ids) {
                    continue;
                }
                
                // 赠送优惠券
                $this->giftCoupons($order['user_id'], $current_coupon_ids);
            }
            
        }
    }


    /**
     * 赠送优惠券
     *
     * @param [type] $user_id
     * @param [type] $coupon_ids
     * @return void
     */
    private function giftCoupons($user_id, $coupon_ids) {
        $where = [
            'id' => ['in', $coupon_ids]
        ];
        $coupons = Coupons::exclusive()->where($where)->select();

        // 循环赠送该商品赠送的优惠券
        foreach ($coupons as $coupon) {
            if ($coupon['gettimestart'] > time() || $coupon['gettimeend'] < time()) {
                // 发放已结束，不在赠送
                \think\Log::error('exclusive_coupon_error:expire;user_id' . $user_id . ',coupon_id:' . $coupon->id);
                continue;
            }

            $getList = UserCoupons::all([
                'user_id' => $user_id,
                'coupons_id' => $coupon->id
            ]);
            if (count($getList) >= $coupon->limit) {
                // 已经赠送足够数量， 不在赠送
                \think\Log::error('exclusive_coupon_error:limit;user_id' . $user_id . ',coupon_id:' . $coupon->id);
                continue;
            }

            if ($coupon->stock <= 0) {
                // 库存不足
                \think\Log::error('exclusive_coupon_error:stock_noenough;user_id' . $user_id . ',coupon_id:' . $coupon->id);
                continue;
            }
            $coupon->stock -= 1;
            $coupon->save();

            $result = UserCoupons::create([
                'user_id' => $user_id,
                'coupons_id' => $coupon->id,
            ]);
        }
    } 
}
